﻿using BasicInformation.Domain;
using Dapper;
using MediatR;
using MySql.Data.MySqlClient;
using MySqlX.XDevAPI.Common;
using SCM.API.Read.Application.Command.Purchase;
using SCM.ErrorCode;
using SCM.Extensions;
using SCM.Infrastructure.Interface;
using System.Text;

namespace SCM.API.Read.Application.Handler.Purchase
{
    public class LookProductHandler : IRequestHandler<LookProductCommand, APIResult<ProductDTO>>
    {
        IDatabaseContext db;

        public LookProductHandler(IDatabaseContext db)
        {
            this.db = db;
        }

        public async Task<APIResult<ProductDTO>> Handle(LookProductCommand request, CancellationToken cancellationToken)
        {
            APIResult<ProductDTO> res = new APIResult<ProductDTO>();

            var sqlBuilder = new StringBuilder();

            sqlBuilder.Append(@"SELECT 
                                        a.ProductCode,
                                        b.ProductName,
                                        b.ProductSpecs,
                                        a.ProductId,
                                        c.UnitId,
                                        c.UnitName,
                                        b.Num,
                                        b.Price,
                                        b.Total,
                                        d.DepotId,
                                        d.DepotName,
                                        e.LocationId,
                                        e.LocationName
                                       
                                FROM ProductModel a 
                                JOIN PurchaseManagementModel b on a.ProductId=b.ProductId
                                JOIN UnitModel c on a.UnitId = c.UnitId 
                                JOIN DepotModel d on a.DepotId = d.DepotId
                                JOIN LocationModel e on a.LocationId = e.LocationId
                                WHERE a.IsDel=0 
                                AND b.IsDel=0 AND c.IsDel=0  AND d.IsDel=0 AND e.IsDel=0 ");



            var parameters = new DynamicParameters();

           

            if (request.ProductId != null)
            {
                sqlBuilder.Append("AND a.ProductId = @ProductId ");
                parameters.Add("ProductId", request.ProductId);
               
            }

           

            var data = await db.DapperConnection.QueryAsync<ProductDTO>(sqlBuilder.ToString(), parameters);
            

            res.Msg = "显示成功";
            res.Code = APIEnum.Success;
            res.Data = data.First();
            return res;
        }
    }
}
